package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DickListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    //根据数据id查询子数据列表
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = getWrapperByParentId(id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        return setDictListChildren(dictList);
    }

    //设置字典里的Children字段
    private List<Dict> setDictListChildren(List<Dict> dictList) {
        for (Dict dict : dictList) {
            boolean flag = hasChildren(dict.getId());
            dict.setHasChildren(flag);
        }
        return dictList;
    }

    //获取子数据的wrapper
    private QueryWrapper<Dict> getWrapperByParentId(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        return wrapper;
    }

    //判断id下方是否有子节点
    private boolean hasChildren(long id){
        QueryWrapper<Dict> wrapper = getWrapperByParentId(id);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }

    //导出数据字典
    @Override
    public void exportDictData(HttpServletResponse response) throws IOException {
        //设置response
        setDictResponse(response);
        //查询数据
        List<Dict> dictList = baseMapper.selectList(null);
        //将dictList转化为将dictEeCoList
        List<DictEeVo> dictEeVoList = changeDictToDictEeVo(dictList);
        //存数据
        EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict")
                 .doWrite(dictEeVoList);
    }

    //导入文件
    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void importDictData(MultipartFile file) throws IOException {
        //在listen中写数据库
        EasyExcel.read(file.getInputStream(),DictEeVo.class,new DickListener(dictMapper));
    }

    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode为Null 那就直接根据Value查询
        if(StringUtils.isEmpty(dictCode)){
            QueryWrapper<Dict> wrapper = getDictWrapperByValue(value);
            return baseMapper.selectOne(wrapper).getName();
        }
        //不为null，具体查
        Long parentId = getDictByDictCode(dictCode).getId();
        Dict dict = getDictByValueAndParentId(value, parentId);

        return dict.getName();
    }

    //用dictCode查询字节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Long parentId = getDictByDictCode(dictCode).getId();
        List<Dict> list = findChildData(parentId);
        return list;
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = getDictQueryByDictCode(dictCode);
        //得到parentId
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;
    }

    private Dict getDictByValueAndParentId(String value, Long parentId) {
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>()
                .eq("parent_id", parentId)
                .eq("value", value));
        return dict;
    }

    private QueryWrapper<Dict> getDictQueryByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        return wrapper;
    }

    private QueryWrapper<Dict> getDictWrapperByValue(String value) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("value", value);
        return wrapper;
    }

    //将dickList转化为dictEeCoList
    private List<DictEeVo> changeDictToDictEeVo(List<Dict> dictList) {
        List<DictEeVo> dictEeVoList = new ArrayList<>();
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVoList.add(dictEeVo);
        }
        return dictEeVoList;
    }

    //设置字典的response
    private void setDictResponse(HttpServletResponse response) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
    }

}